package Leo.serviceClient.config;

import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@Component
@ServletComponentScan //让WebFilter注解生效
@WebFilter(urlPatterns = "/hystrixDemo/*",filterName = "hystrixFilter")
public class HystrixFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 缓存和合并请求功能都是需要先初始化请求上下文才能实现，因为此功能是在一次访问请求中触发
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HystrixRequestContext context = HystrixRequestContext.initializeContext();
        try {
            System.out.println("触发过滤器");
            filterChain.doFilter(servletRequest, servletResponse);
        }finally {
            context.shutdown();
        }
    }

    public void destroy() {

    }
}
